const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const fs = require('fs-extra')
const htmlWebpackExternalsPlugin = require('html-webpack-externals-plugin')
const chalk = require('chalk')
const glob = require('glob')
let fileDirs = glob.sync('./src/pages/*')
function setupIndexTemplate() {
	fileDirs.forEach((fileDir)=>{
		let dirName = fileDir.match(/pages\/(.*)$/)[1]
		componentName = dirName.replace(dirName[0],dirName[0].toUpperCase())
		let exist = fs.pathExistsSync(`${fileDir}/${componentName}.js`)
		if(!exist) return
		try {
			let indexDir = `${fileDir}/index.js`
			let template = `import React from 'react';
				import ReactDOM from 'react-dom';
				import ${componentName} from './${componentName}';
				ReactDOM.render(
					<${componentName} />,
					document.getElementById('root')
				);
			`.replace(/\t/g,'')
			fs.ensureFileSync(indexDir)
			fs.outputFileSync(indexDir,template)
		} catch (error) {
			chalk.red(`${fileDir}/${componentName}.js 未默认导出`)
		}
	})
}
function setupMpa() {
	const entry = {}
	const htmlWebpackPlugin = []

	const entryFiles = fileDirs.map(fileDir=>fileDir+'/index.js')
	entryFiles.forEach((entryFile)=>{
		const [,pageName] = entryFile.match(/pages\/(.*)\/index.js$/)
		entry[pageName] = entryFile
		htmlWebpackPlugin.push(new HtmlWebpackPlugin({
			template: path.join(__dirname,'index.html'),
			filename: `${pageName}.html`,
			chunks: [pageName],
		}))
	})
	return {
		entry,
		htmlWebpackPlugin
	}
}
setupIndexTemplate()
const {entry,htmlWebpackPlugin} = setupMpa()
module.exports = {
	mode: 'development',
	entry,
	output: {
		filename: '[name]-[chunkhash:8].js',
		path: path.resolve(__dirname,'dist')
	},
	devtool: process.env.NODE_ENV === 'production'?false:'source-map',
	module: {
		rules: [
			{
				test:/\.(jsx|ts|js)$/,
				loader:'babel-loader',
				exclude:/node_modules/,
			},
		]
	},
	plugins: [
		new htmlWebpackExternalsPlugin({
			externals:[
				{
					module:'react',
					entry: 'umd/react.production.min.js',
					global:'React'
				},
				{
					module:'react-dom',
					entry: 'umd/react-dom.production.min.js',
					global:'ReactDOM'
				}
			]
		})
	].concat(htmlWebpackPlugin)
}